
package misc

import (
	"time"
	"dhfshop/models"
	"dhfshop/models/consts"
	//"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type TimerTask struct {
	Id           int64     `orm:"column(id);pk;auto" json:"id" form:"id"` //
	//PartnerId  int64     `orm:"column(partner_id);index" json:"partner_id" form:"partner_id"` //组织编号
	//StoreId    int64     `orm:"column(store_id)" json:"store_id" form:"store_id"`             //门店编号
	TaskId       int64     `orm:"column(task_id);unique" json:"task_id" form:"task_id"`          //任务编号
	TaskBody     string    `orm:"column(task_body)" json:"task_body" form:"task_body"`          //任务内容
	OuterId      string    `orm:"column(outer_id)" json:"outer_id" form:"outer_id"`             //业务单号
	CreatedAt    time.Time `orm:"column(created_at);auto_now_add;type(datetime)" json:"-"`
	CreatedAtStr string    `orm:"-" json:"created_at"`
	UpdatedAt    time.Time `orm:"column(updated_at);auto_now;type(datetime)" json:"-"`
	UpdatedAtStr string    `orm:"-" json:"updated_at"`
	Note         string    `orm:"column(note);size(1024);null" json:"note" form:"note"`         //备注
}

func init() {
	orm.RegisterModel(new(TimerTask))
}

func AddTimerTask(task *TimerTask) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(task)
	return
}

func GetTimerTaskByTaskId(taskId int64) (task *TimerTask, err error) {
	o := models.GetDefaultDB()
	task = &TimerTask{TaskId: taskId}
	if err = o.Read(task, "TaskId"); err != nil {
		return
	}
	return
}

func GetAllTimerTasks(taskId int64, start, end string, offset, limit int)(lists []*TimerTask, err error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(TimerTask))
	if len(start) == 19 {
		if startTime, err := time.Parse(consts.DATETIME_FORMAT, start); err == nil {
		    qs = qs.Filter("created_at__gte", startTime)
		}
	}
	if len(end) == 19 {
		if endTime, err := time.Parse(consts.DATETIME_FORMAT, end); err == nil {
	        qs = qs.Filter("created_at__lte", endTime)
	    }
	}
	if taskId > 0 {
	    qs = qs.Filter("task_id", taskId)
	}
	if _, err = qs.Limit(limit, offset).All(&lists); err == nil {
		return lists, nil
	}
	return nil, err
}

func UpdateTimerTaskById(m *TimerTask, fields ...string) error {
	o := models.GetDefaultDB()
	v := TimerTask{Id: m.Id}
	if err := o.Read(&v); err != nil {
		return err
	}
	_, err := o.Update(m, fields...)
	return err
}

func DeleteTimerTaskByTaskId(taskId int64) (err error) {
	o := models.GetDefaultDB()
	v := TimerTask{TaskId: taskId}
	if err = o.Read(&v, "TaskId"); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return nil
		}
	}
	return
}
